const BASE_URL = "http://www.pudge.wang:4000";

interface Params {
  [propname: string]: any;
}

const http = {
  get(url: string, params?: Params) {
    // params {a: 10, b: 20}  ->  url: "?a=10&b=20"
    if (params) {
      const arr = Object.keys(params); // arr ["a", "b"]
      const arr2 = arr.map((item: string) => item + "=" + params[item]); // arr2: ["a=10", "b=20"]
      const str = "?" + arr2.join("&"); // str "?a=10&b=20"
      url += str;
    }

    return fetch(BASE_URL + url)
      .then((response) => response.json())
      .then((res) => {
        if (res.status === "0") {
          return res;
        }
      });
  },
  post(url: string, data?: object) {
    return fetch(BASE_URL + url, {
      method: "post",
      headers: {
        "content-type": "application/json",
      },
      body: JSON.stringify(data),
    })
      .then((response) => {
        return response.json();
      })
      .then((res) => {
        if (res.status === "0") {
          return res;
        }
      });
  },
};

export default http;
